import type { App } from 'vue'
import is from '@/utils/is'
import { useMainStore } from '@/store/useMainStore'

export function setupPermission(app: App) {
  app.directive('permission', {
    mounted: (el, binding) => {
      const value = binding.value
      if (!value) return
      if (!hasPermission(value)) {
        el.parentNode?.removeChild(el)
      }
    }
  })
}

export function hasPermission(value?: number[] | number, def = true): boolean {
  const mainStore = useMainStore()
  if (!value) {
    return def
  }

  if (is.array(value)) {
    return value.some((role) => mainStore.roles.includes(role))
  } else {
    return mainStore.roles?.includes(value)
  }
}

export function hasOnePermission(value?: number, def = true): boolean {
  const mainStore = useMainStore()
  if (!value) {
    return def
  }

  return mainStore.roles[0] === value
}
